{extend name="../../base/view/common/base" /}
<!-- 主体 -->
{block name="body"}
<div id="tip_modal">
    <form class="layui-form p-4">
        <h3 class="pb-3">功能菜单/节点</h3>
        <table class="layui-table layui-table-form">


            <tr>
                <td class="layui-td-gray">单据日期<font>*</font>
                </td>
                <td>
                    <input type="text" class="layui-input" value="{$detail.orderDate|default=$defalutTime}" readonly name="orderDate" id="orderDate" placeholder="选择时间"
                           required>
                </td>
                <td class="layui-td-gray">备注
                </td>

                <td>
                    <input type="text" class="layui-input" value="{$detail.remark|default=''}"  name="remark" placeholder="输入备注">
                </td>
            </tr>
            <tr>
                <td>制单人</td>
                <td>
                    <span>{$detail.username|default=''}</span>
                </td>
                <td class="layui-td-gray">状态<font>*</font>
                </td>
                <td>
                    <select name="status" disabled>
                        {foreach [['id'=>1,'name'=>'草稿'],['id'=>2,'name'=>'待确认'],['id'=>3,'name'=>'已确认']] as $st}
                        <option value="{$st.id}" {if isset($detail.status)&&$detail.status==$st.id } selected {/if}>{$st.name}</option>
                        {/foreach}
                    </select>

                </td>

            </tr>
            <tr>
                <td colspan="6"><h3>明细</h3></td>
            </tr>
            <tr>
                <td colspan="6">
                    {if !isset($detail.status)||$detail.status==1}
                    <a href="javascript:" data-modal="{:url('addMx')}" class="layui-btn layui-btn-primary">选择物料</a>
                {/if}
                </td>
            </tr>
            <tr>

           <td colspan="6">
            <table class="layui-table tableMany">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>规格型号</th>
                    <th>单位</th>
                    <th>计划数量</th>
                    <th>计划时间</th>
                    <th>BOM版本</th>
                    <th>工艺路线</th>
                    <th>操作</th>
                </tr>
                </thead>
                {if isset($mxList)}
                <tbody id="mxTbdy">
                {volist name='mxList' id='ml' key='k'}
                <tr>
                    <td><span class="xuhao">{$k}</span>
                        <input type="hidden" name="mxid[]" value="{$ml.id}">
                        <input type="hidden" name="material_id[]" value="{$ml.material_dossier_id}"></td>
                    <td>{$ml.bar_code}</td>
                    <td>{$ml.mdName}</td>
                    <td>{$ml.specs}</td>
                    <td>{$ml.unit}</td>
                    <td>
                        <input type="text" value="{$ml.num}" class="layui-input " maxlength='9' required
                               lay-verify="required" onkeyup="digitalFiltering(this,0)" placeholder="请输入数量"
                               autocomplete="off" min="0" max="999999" name="num[]">
                    </td>
                    <td>
                        <input type="text" class="layui-input planned_time" value="{$ml.planned_time|default=''}" readonly name="planned_time[]" id="planned_time_{$k}" placeholder="选择时间" required>

                    </td>
                    <td>
                        <select name="bom_id[]" >
                            {volist name='ml.bom' id='bl'}
                            <option value="{$bl.id}" {if $ml.bom_id == $bl.id} selected {/if}>{$bl.id}</option>
                            {/volist}
                        </select>
                    </td>
                    <td>
                        <select name="craft_route_id[]" id="">
                            {volist name='ml.craftRoute' id='cl'}
                            <option value="{$cl.id}" {if $ml.craft_route_id == $cl.id} selected {/if}>{$cl.name}</option>
                            {/volist}
                        </select>
                    </td>
                    <td>
                        {if !isset($detail.status)||$detail.status==1}
                        <a href="javascript:" class="layui-btn layui-btn-xs layui-btn-danger"
                           onclick="delMx('{$ml.id}',this)">删除</a>
                        {/if}
                    </td>
                </tr>
                {/volist}
                </tbody>
                {else}
                <tbody id="mxTbdy">
                </tbody>
                {/if}
            </table>
           </td>
            </tr>
    {if isset($detail.status)&&$detail.status>1}
            <tr>
                <td colspan="6"><h3>原材料明细</h3></td>
            </tr>
            <tr>
                <td colspan="6">
                {if $detail.status==2}
                <a href="javascript:" onclick="getBOMData()"  class="layui-btn layui-btn-primary">BOM获取</a>
                {/if}
                    {if $detail.status>1}
                    <a href="{:url('exportChaQue')}?id={$detail.id}" target="_blank" id="exPortChaQue"  class="layui-btn layui-btn-primary">导出差缺</a>
                    {/if}
                </td>
            </tr>
            <tr>
                <td colspan="6">
                    <table class="layui-table tableYcl">
                        <thead>
                        <tr>
                            <th>序号</th>
                            <th>物料编码</th>
                            <th>物料名称</th>
                            <th>规格型号</th>
                            <th>单位</th>
                            <th>仓库</th>
                            <th>预计数量</th>
                            <th>库存数量</th>
                            <th>出库数量</th>
                            <th>差缺</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="bomTbody">
                        {if $yclList}
                        {volist name='yclList' id= 'yl' key='yk'}
                        <tr>
                            <td><span class="xuhao">{$yk}</span>
                                <input type="hidden" name="ycl_material_dossier_id[]" value="{$yl.material_dossier_id}">
                                <input type="hidden" name="ycl_yjNum[]" value="{$yl.yjNum}">
                            </td>
                            <td>{$yl.bar_code}</td>
                            <td>{$yl.mdName}</td>
                            <td>{$yl.specs}</td>
                            <td>{$yl.unit}</td>
                            <td><select name="wId[]" id="wid_{$yk}" lay-filter="wIds">
                                {volist name='warehouse' id='whs'}
                                <option title="{$yl.material_dossier_id}" {if $yl.wId==$whs.id} selected {/if} value="{$whs.id}">{$whs.name}</option>
                                {/volist}
                            </select></td>
                            <td><span id="yjNum_{$yk}">{$yl.yjNum}</span></td>
                            <td> <span id="kcNum_{$yk}">{$yl.kcNum}</span> <input type='hidden' name="kcNum[]" id='kcInput_{$yk}' value='{$yl.kcNum}'></td>
                            <td><input type="text" class="layui-input"   lay-verify="required" value="{$yl.ckNum}" name="ycl_ckNum[]" onkeyup="digitalFiltering(this,2)"></td>
                            <td> <span id="cahqueSpan_{$yk}">{$yl.chaque}</span><input type="hidden" id="chaque_{$yk}" name="chaque[]" value="{$yl.yjNum-$yl.kcNum}"></td>
                            <td>
                                {if isset($detail.status)&&$detail.status==2}
                                <a href="javascript:" class='layui-btn layui-btn-danger layui-btn-xs' onclick='removetr(this)'>删除</a>
                            {/if}
                            </td>
                        </tr>
                        {/volist}
                        {/if}
                        </tbody>
                    </table>
                </td>
            </tr>
            {/if}
        </table>
        <div class="py-3">
            <input type="hidden" name="id" value="{$id}">
            {if !isset($detail.status)||$detail.status<3}
            <button class="layui-btn layui-btn-normal" type="button" id="sub" lay-submit="" lay-filter="webform1">{if !isset($detail.status)||$detail.status==1}
                保存{else}保存原材料{/if} </button>
            {/if}
            {if isset($detail.status)&&$detail.status==1}
            <button type="button" class="layui-btn layui-btn-normal" onclick="onSub()">
                提交
            </button>
            {/if}
            {if isset($detail.status)&&$detail.status==2&&(isset($yclList)&&$yclList)}
            <button type="button" class="layui-btn layui-btn-normal" onclick="onSure()">确认</button>
            {/if}
            {if isset($detail.status)&&$detail.status==3}
            <button type="button" class="layui-btn layui-btn-danger" onclick="onCancel()">撤回</button>
            {/if}
        </div>
    </form>
</div>

{/block}
<!-- /主体 -->
{block name="script"}
<script>

    const moduleInit = ['tool'];

    let isSub = 2;

    function gouguInit() {
        var form = layui.form, tool = layui.tool;
        //监听提交
        form.on('submit(webform1)', function (data) {
            let callback = function (e) {
                isSub = 2;
                layer.msg(e.msg);
                if (e.code == 0) {
                    setTimeout(function () {
                        parent.parent.location.reload();
                    }, 1000);
                }
            }
            if (isSub == 2) {
                isSub = 1
                tool.post("{:url('add')}", data.field, callback);
            }
            return false;
        });

        // layui.use(['form'], function () {
        //     var form = layui.form;
        //     form.render();
        // });
        form.on('select(materRial)', function (data) {
            var selectedTitle = '';
            $('#materRial option').each(function () {
                if ($(this).val() == data.value) {
                    selectedTitle = $(this).attr('title');
                }
            });
            console.log('ttt', selectedTitle)
            $('#spces').text(selectedTitle)
        }); // select(lay-filter属性的值)
        //动态获取联动
        form.on('select(warehouse_id)', function (data) {
            var mxIndex = 1;
            var sid= $(data.elem).attr('id')
            var wid=data.value;
            $('#'+sid+' option').each(function () {
                if ($(this).val() == data.value) {
                    mxIndex = $(this).attr('title');
                }
            });
            $("#locator_"+mxIndex+"").empty();
            var optionStr='';
            if (wid!=''){
              $.ajax({
                  url:'/home/api/getWarHoseDetail',
                  type:'post',
                  dataType:'json',
                  data:{id:wid},
                  success:function (res) {
                      if (res.code==0){
                          let data=res.data;
                          for(var i=0;i<data.length;i++){
                              optionStr+=" <option value='"+data[i].id+"'>"+data[i].name+"</option>";
                          }
                      }else {
                          optionStr+=" <option value=''>暂无数据</option>";
                      }
                      $("#locator_"+mxIndex+"").append(optionStr);
                      form.render();
                  }

              })
            }else {
                optionStr+=" <option value=''>请选择仓库</option>";
                $("#locator_"+mxIndex+"").append(optionStr);
                form.render();
            }


        }); // select(lay-filter属性的值)
        //弹窗
        var treeTable = layui.table, form = layui.form;
        var tableIns = treeTable.render({
            elem: '#mxTable'
            , url: "{:url('addMx')}"
            , method: 'post'
            , toolbar: '#toolbarDemo',
            defaultToolbar: []
            , cellMinWidth: 80
            , cols: [[
                {type: 'checkbox', fixed: 'left'},
                {fixed: 'left', field: 'id', title: 'ID', unresize: true, hide: true},
                {field: 'id', width: 80, title: 'ID号', align: 'center'}
                , {field: 'specs', title: '规格型号'}
                , {field: 'name', title: '名称'}
                , {field: 'bar_code', title: '编码'}
                , {field: 'unit', title: '单位'}
            ]]
            , page: true
        });
        //监听搜索提交
        form.on('submit(webform)', function (data) {
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });
        //表头工具栏事件
        treeTable.on('toolbar(mxTable)', function (obj) {
            var checkStatus = treeTable.checkStatus(obj.config.id);
            console.log(checkStatus)
            switch (obj.event) {
                case 'add':
                    break;
                case 'subt':
                    var data = checkStatus.data;
                    var ids = []
                    if (data.length) {
                        data.forEach(function (value, index) {
                            ids.push(value)
                        })
                        saveAddMx(ids)
                        layer.close(layTip)

                    } else {
                        layer.msg('请选择数据');
                    }

                    break;
                case 'import':

                    break;

            }
            ;
        })
        laydate.render({
            elem: '#orderDate'
            , type: 'date',
        });
        laydate.render({
            elem: '.planned_time'
            , type: 'date',
        });

        form.on('select(wIds)', function (data) {
            let wId=data.value;
            let seId=$(data.elem).attr('id')
            let mdId='';
            $('#'+seId+' option').each(function () {
                if ($(this).val() == data.value) {
                    mdId = $(this).attr('title');
                }
            });
            if (!wId||!mdId){
                layer.msg('参数有误')
                return;
            }
            let aa=seId.split('_')
            $.ajax({
                url:"{:url('Api/getMdKuCun')}",
                type:'post',
                dataType:'json',
                data:{mdId:mdId,wId:wId},
                success:function (res) {
                    console.log('res',res)
                    if (res.code==0){
                        let resData=res.data
                        let kcNum=resData.kcNum;
                        let sp_id='kcNum_'+aa[1];
                        let yjNum=$('#yjNum_'+aa[1]).text()
                        let chaque=parseFloat(yjNum-kcNum)
                        chaque=chaque<0?0:chaque;
                        $("#"+sp_id).text(kcNum)
                        $("#cahqueSpan_"+aa[1]).text(chaque)
                        $("#chaque_"+aa[1]).val(chaque)
                        $("#kcInput_"+aa[1]).val(resData.kcNum)
                    }else {
                        layer.msg(res.msg)
                    }
                }
            })
        }); // select(lay-filter属性的值)
    }
</script>
<script>
    function saveAddMx(ojb) {
        var lastListItem = $('.tableMany tr:last');
        let aa = $(lastListItem).find(".xuhao")
        let len = $(aa).text()
        console.log('leng:', len)
        if (!parseInt(len)) {
            len = 0;
        }
        let index = parseInt(len) + 1;
        let str = '';
        for (var i = 0; i < ojb.length; i++) {
            var bom=ojb[i].bom;
            var craft=ojb[i].craftRoute;
            var bomStr='';
            var craftStr='';
            for (var j=0;j<bom.length;j++){
                bomStr+='<option value="'+bom[j].id+'" >'+bom[j].id+'</option>';
            }
            for (var k=0;k<craft.length;k++){
                craftStr+='<option value="'+craft[k].id+'" >'+craft[k].name+'</option>';
            }
            str += "  <tr>\n" +
                "                <td> <span class=\"xuhao\">" + index + "</span> <input type=\"hidden\" name=\"mxid[]\" value=\"\"><input type=\"hidden\" name=\"material_id[]\" value=\"" + ojb[i].id + "\"></td>\n" +
                "                <td> " + ojb[i].bar_code + " </td>\n" +
                "                <td> " + ojb[i].name + " </td>\n" +
                "                <td>" + ojb[i].specs + " </td>\n" +
                "                <td>" + ojb[i].unit + " </td>\n" +
                "                <td> <input type=\"text\" value='' class=\"layui-input \" maxlength='9' required\n" +
                "                               lay-verify=\"required\" onkeyup=\"digitalFiltering(this,0)\" placeholder=\"请输入数量\"\n" +
                "                               autocomplete=\"off\" min=\"0\" max=\"999999\" name=\"num[]\"></td>\n" +
                "                <td>                        <input type=\"text\" class=\"layui-input planned_time\" value='' readonly name=\"planned_time[]\"  placeholder=\"选择时间\" required>\n</td>\n" +
                "                <td>     <select name=\"bom_id[]\" >"+bomStr+"</select></td>\n" +
                "                <td> <select name=\"craft_route_id[]\" id=\"\">"+craftStr+"</select></td>\n" +
                "                <td>\n" +
                "                    <a href=\"javascript:\" class='layui-btn layui-btn-danger layui-btn-xs' onclick='removetr(this)'>删除</a>\n" +
                "                </td>\n" +
                "            </tr>";
            index++;
        }
        $("#mxTbdy").append(str)
        layui.use(['form','laydate'], function () {
            var form = layui.form;
            var laydate = layui.laydate;
            laydate.render({
                elem: '.planned_time'
                , type: 'date',
            });
            form.render();
        });
    }

    function removetr(e) {
        $(e).parent().parent().remove()
    }

    function delMx(id = '', e) {
        if (id == '') {
            layer.msg('请选择数据')
            return;
        }
        $.ajax({
            url: "{:url('removeMx')}",
            type: 'post',
            dataType: 'json',
            data: {id: id},
            success: function (res) {
                if (res.code != 0) {
                    layer.msg(res.msg)
                } else {
                    removetr(e)
                }
            },
            error(e) {
                layer.msg('网络错误，请稍后')
            }
        })
    }


    let is_sure=2;
    function onSure() {
        let id="{$id}";
        if (id==0){
            layer.msg('操作有误');
            return;
        }
        if (is_sure==1){
            return;
        }
        is_sure=1;
        $.ajax({
            url:"{:url('onSure')}",
            type:'post',
            dataType:'json',
            data:{id:id},
            success:function (res) {
                is_sure=2;
                layer.msg(res.msg)
                if (res.code == 0) {
                    setTimeout(function () {
                        parent.parent.location.reload();
                    }, 1000);
                }
            },
            error(e){
                layer.msg('网络错误，请稍后重试')
                is_sure=2
            }
        })
    }
    let is_sub=2;
    function onSub() {
        let id="{$id}";
        if (id==0){
            layer.msg('操作有误');
            return;
        }
        if (is_sub==1){
            return;
        }
        is_sub=1;
        $.ajax({
            url:"{:url('confirm')}",
            type:'post',
            dataType:'json',
            data:{id:id},
            success:function (res) {
                is_sub=2;
                layer.msg(res.msg)
                if (res.code == 0) {
                    setTimeout(function () {
                        parent.parent.location.reload();
                    }, 1000);
                }
            },
            error(e){
                layer.msg('网络错误，请稍后重试')
                is_sub=2
            }
        })
    }
    let is_cancel=2;
    function onCancel() {
        let id="{$id}";
        if (is_cancel==1){
            return;
        }
        is_cancel=1;
        $.ajax({
            url:"{:url('onCancel')}",
            type:'post',
            dataType:'json',
            data:{id:id},
            success:function (res) {
                is_cancel=2;
                layer.msg(res.msg)
                if (res.code == 0) {
                    setTimeout(function () {
                        parent.parent.location.reload();
                    }, 1000);
                }
            },
            error(e){
                layer.msg('网络错误，请稍后重试')
                is_cancel=2
            }
        })
    }

    let is_getBOm=2;
    function getBOMData() {
        let checkBomIds=[];
        let nums=[];
        let aa=document.getElementsByName('bom_id[]')
        let bb=document.getElementsByName('num[]');
        console.log('bb',bb)
        for (var i=0;i<aa.length;i++){
            if (aa[i].value!=''&&aa[i].value!=0){
                checkBomIds.push(aa[i].value)
            }
        }
        for (var j=0;j<bb.length;j++){
            if (bb[j].value==''){
                bb[j].value=0;
            }
            nums.push(bb[j].value);
        }
        if (checkBomIds.length<1){
            layer.msg('未获取到BOM版本')
            return;
        }
        if (is_getBOm==1){
            return;
        }
        $.ajax({
            url:"{:url('Api/getBomDetail')}",
            type:'post',
            dataType:'json',
            data:{bomIds:checkBomIds.join(','),nums:nums.join(',')},
            success:function (res) {
                $("#bomTbody").empty();
                is_getBOm=2;
                layer.msg(res.msg)
                if (res.code==0){
                    let data=res.data;
                    let str='';
                    var lastListItem = $('.tableYcl tr:last');
                    let aa = $(lastListItem).find(".xuhao")
                    let len = $(aa).text()
                    console.log('leng:', len)
                    if (!parseInt(len)) {
                        len = 0;
                    }
                    let index = parseInt(len) + 1;
                    for (var i=0;i<data.length;i++){
                        let detail=data[i];
                        let chaque=parseFloat(detail.yjNum-detail.kcNum);
                        chaque=chaque<0?0:chaque;
                        let whareStr='';
                   "     {volist name='warehouse' id='wh'}"
                        if(detail.wId =={$wh['id']}){
                        whareStr+="<option title='"+detail.mdId+"' selected value='{$wh.id}'>{$wh.name}</option> ";
                        }else{
                            whareStr+="<option title='"+detail.mdId+"' value='{$wh.id}'>{$wh.name}</option> ";
                        }
                      "  {/volist}"
                        str+="<tr>\n" +
                            "                            <td> <span class='xuhao'>"+parseInt(i+1)+"</span>\n" +
                            "                                <input type=\"hidden\" name=\"ycl_material_dossier_id[]\" value='"+detail.mdId+"'>\n" +
                            "                                <input type=\"hidden\" name=\"ycl_yjNum[]\" value='"+detail.yjNum+"'>\n" +
                            "                            </td>\n" +
                            "                            <td>"+detail.bar_code+"</td>\n" +
                            "                            <td>"+detail.mdName+"</td>\n" +
                            "                            <td>"+detail.specs+"</td>\n" +
                            "                            <td>"+detail.unit+"</td>\n" +
                            "                            <td><select name='wId[]' id='wid_"+i+"' lay-filter='wIds'>"+whareStr+"</select></td>\n" +
                            "                            <td> <span id='yjNum_"+i+"'></span>"+detail.yjNum+"</td>\n" +
                            "                            <td><span id='kcNum_"+i+"'>"+detail.kcNum+"</span><input type='hidden' name='kcNum[]' id='kcInput_"+i+"' value='"+detail.kcNum+"'></td>\n" +
                            "                            <td><input type=\"text\" value='"+detail.yjNum+"'  lay-verify=\"required\" class=\"layui-input\" name=\"ycl_ckNum[]\" onkeyup=\"digitalFiltering(this,0)\"></td>\n" +
                            "                            <td><span id='cahqueSpan_"+i+"'>"+chaque+"</span><input type='hidden' id='chaque_"+i+"' name='chaque[]' value='"+chaque+"'></td>\n" +
                            "                            <td><a href=\"javascript:\" class='layui-btn layui-btn-danger layui-btn-xs' onclick='removetr(this)'>删除</a></td>\n" +
                            "                        </tr>";
                    }
                    $("#bomTbody").append(str)
                }
        form.render();
            },
            error(e){
                layer.msg('网络错误，请稍后重试')
                is_getBOm=2
            }
        })
    }
</script>
{/block}
<!-- /脚本 -->